package com.andatsoft.laisim.activity;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.view.SlimProgressBar;
import com.andatsoft.laisim.view.SlimProgressBar.SlimProgressClicked;

public class MiniPlayerActivity extends BaseActivity implements
		OnPreparedListener, OnCompletionListener {
	private MediaPlayer mMediaPlayer;
	private Button mBtnPlay;
	private Button mBtnClose;
	private ImageView mImgAlbum;
	private TextView mTvTitle;
	private TextView mTvArtist;
	private SlimProgressBar mProgress;

	private String mSongUrl;
	private Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mini_player);
		initViews();
		setAlpha(findViewById(R.id.layout_mini_player), 0.8f);
		setAlpha(findViewById(R.id.layout_mini_player_header), 0.5f);
		initMedia();
		setupListenner();
		fillData();
	}

	private void initMedia() {
		mSongUrl = getIntent().getExtras().getString(
				Common.INTENT_DATA_SONG_URI);
		mSongUrl = mSongUrl.substring(7, mSongUrl.length());
		mSongUrl = Uri.decode(mSongUrl);
		mMediaPlayer = new MediaPlayer();
		mMediaPlayer.setOnPreparedListener(this);
		mMediaPlayer.setOnCompletionListener(this);
		try {
			mMediaPlayer.setDataSource(mSongUrl);
			mMediaPlayer.prepareAsync();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void initViews() {
		mBtnPlay = (Button) findViewById(R.id.btn_play_pause_mini_player);
		mBtnClose = (Button) findViewById(R.id.btn_close_mini_player);
		mTvTitle = (TextView) findViewById(R.id.tv_title_mini_player);
		mTvArtist = (TextView) findViewById(R.id.tv_artist_mini_player);
		mImgAlbum = (ImageView) findViewById(R.id.img_album_art_mini_player);
		mProgress = (SlimProgressBar) findViewById(R.id.progress_mini_player);
	}

	private void setupListenner() {
		mBtnClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mHandler.removeCallbacks(mUpdateUI);
				if (mMediaPlayer != null) {
					if (mMediaPlayer.isPlaying())
						mMediaPlayer.stop();
				}
				overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out);
				MiniPlayerActivity.this.finish();
			}
		});

		mBtnPlay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (mMediaPlayer != null) {
					if (mMediaPlayer.isPlaying()) {
						mMediaPlayer.pause();
						mBtnPlay.setBackgroundResource(R.drawable.btn_notification_play);
						mHandler.removeCallbacks(mUpdateUI);
					} else {
						mMediaPlayer.start();
						mBtnPlay.setBackgroundResource(R.drawable.btn_notification_pause);
						mHandler.postDelayed(mUpdateUI, 250);
					}
				}
			}
		});

		mProgress.setOnSlimClicked(new SlimProgressClicked() {

			@Override
			public void onClick(int newProgress) {
				mMediaPlayer.seekTo(newProgress);
			}
		});
	}

	private void fillData() {
		// get song info
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		Log.i("mini player", "path: " + mSongUrl);
		try {
			retriever.setDataSource(mSongUrl);
			String value = retriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
			if (value == null)
				value = mSongUrl.substring(mSongUrl.lastIndexOf("/") + 1,
						mSongUrl.length());
			mTvTitle.setText(value);
			value = retriever
					.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
			if (value == null)
				value = getString(R.string.common_text_unknown_song_info);
			mTvArtist.setText(value);
			byte[] pic = retriever.getEmbeddedPicture();
			if (pic != null) {
				Bitmap bm = BitmapFactory.decodeByteArray(pic, 0, pic.length,
						null);
				mImgAlbum.setImageBitmap(Bitmap.createScaledBitmap(bm, 100,
						100, true));
			}

		} catch (IllegalArgumentException ie) {
			ie.printStackTrace();
		} catch (RuntimeException re) {
			re.printStackTrace();
		}
	}

	private Runnable mUpdateUI = new Runnable() {
		public void run() {
			if (mMediaPlayer == null)
				return;
			int cur = 0;
			try {
				cur = mMediaPlayer.getCurrentPosition();
			} catch (Exception e) {
				cur = 0;
			}

			mProgress.setProgress(cur);
			mHandler.postDelayed(mUpdateUI, 250);
		}
	};

	@Override
	public void onPrepared(MediaPlayer mp) {
		mMediaPlayer.start();
		mBtnPlay.setBackgroundResource(R.drawable.btn_notification_pause);
		mProgress.setMax(mMediaPlayer.getDuration());
		mHandler.post(mUpdateUI);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mMediaPlayer != null) {
			mMediaPlayer.release();
		}
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		mBtnPlay.setBackgroundResource(R.drawable.btn_notification_play);
		mHandler.removeCallbacks(mUpdateUI);

	}
}
